import json
import random

from re_common.baselibrary.tools.all_requests.mrequest import MRequest
from re_common.baselibrary.utils.core.mdeprecated import retry_func_async, try_except2_async
from re_common.baselibrary.utils.core.requests_core import INSIDE_HEADERS

from apps.allsubdb.proxies_control.models import PostProxy
from apps.crawler_platform.core_callback.err_callback import all_client_back_callback
from apps.crawler_platform.core_platform.g_model import InputPlatformModel
from apps.crawler_platform.util.requestapihelper import RequestApiHelper
from settings import URLDISTRIBUTED, get_settings


class ProxyHelper(object):
    @classmethod
    @try_except2_async(callback=all_client_back_callback, is_print=True)
    @retry_func_async(retry_times=3, sleep_time=1)
    async def get_proxy(cls, self):
        """
        获取代理接口
        self: 主类的self obj
        """
        task_name, task_tag = self.pm.task_name, self.pm.task_tag
        pm = self.pm
        url = await URLDISTRIBUTED.get_redis_proxy_one()
        if self.input.input_code.strip() != "":
            if "10000" in self.input.input_code.split(";"):
                url = await URLDISTRIBUTED.get_redis_proxy_one()
            elif "10001" in self.input.input_code.split(";"):
                url = await URLDISTRIBUTED.get_qingting_proxy_one()
            elif "10003" in self.input.input_code.split(";"):
                url = await URLDISTRIBUTED.get_school_proxy_one()
            elif "10002" in self.input.input_code.split(";"):
                pm.proxy = random.choice(self.input.input_msg.split(";"))
                self.add_process_info("使用了传上来的代理")
                return True, {}
        elif pm.task_setting.proxy_type in ("qingting", "redis_taiyang"):
            if pm.task_setting.proxy_type == "qingting":
                url = await URLDISTRIBUTED.get_qingting_proxy_one()
            elif pm.task_setting.proxy_type == "redis_taiyang":
                url = await URLDISTRIBUTED.get_redis_proxy_one()
        else:
            data = InputPlatformModel(
                data=PostProxy(task_name=task_name,
                               task_tag=task_tag
                               )).json()
            rrq = RequestApiHelper.get_rrq()
            kwargs = {
                "rrq": rrq,
                "header": INSIDE_HEADERS,
                "url": get_settings().PROXY_URL,
                "timeout": 30,
                "data": data,
                "moths": MRequest.POST,
                "middler_list": [rrq.status_code_middlerwares,
                                 rrq.is_none_html_middlerwares,
                                 rrq.is_null_html_middlerwares,
                                 rrq.msg_status_code_middlerwares]
            }
            bools, status_msg_dict = await RequestApiHelper.proxy_api(**kwargs)
            if bools:
                pm.proxy = json.loads(rrq.html)["data"]
                if pm.proxy == "":
                    bools = False
            if not bools:
                self.add_process_info(self.step_info)

            return bools, status_msg_dict

        rrq = RequestApiHelper.get_rrq()
        kwargs = {
            "rrq": rrq,
            "header": INSIDE_HEADERS,
            "url": url,
            "timeout": 30,
            "moths": MRequest.GET,
            "middler_list": [rrq.status_code_middlerwares,
                             rrq.is_none_html_middlerwares,
                             rrq.is_null_html_middlerwares,
                             rrq.msg_status_code_middlerwares]
        }
        bools, status_msg_dict = await RequestApiHelper.proxy_api(**kwargs)
        if bools:
            pm.proxy = json.loads(rrq.html)["data"]["proxy"]
            if pm.proxy == "":
                bools = False
        if not bools:
            self.add_process_info(self.step_info)
        return bools, status_msg_dict

    @classmethod
    @try_except2_async(callback=all_client_back_callback, is_print=True)
    @retry_func_async(retry_times=3, sleep_time=1)
    async def get_proxy_policy_url_conn(cls):
        """
        获取代理接口
        用于政策url测试连接
        self: 主类的self obj
        """

        url = await URLDISTRIBUTED.get_qingting_proxy_one()

        rrq = RequestApiHelper.get_rrq()
        kwargs = {
            "rrq": rrq,
            "header": INSIDE_HEADERS,
            "url": url,
            "timeout": 30,
            "moths": MRequest.GET,
            "middler_list": [rrq.status_code_middlerwares,
                             rrq.is_none_html_middlerwares,
                             rrq.is_null_html_middlerwares,
                             rrq.msg_status_code_middlerwares]
        }
        bools, status_msg_dict = await RequestApiHelper.proxy_api(**kwargs)
        if bools:
            proxy = json.loads(rrq.html)["data"]["proxy"]
            if proxy == "":
                bools = False
        else:
            proxy = ""
        return bools, proxy